package cn.kgc.tangcco.intercepter;

import cn.kgc.tangcco.configurer.ParamConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 李昊哲
 * @Description
 * @create 2020/12/25 10:59
 */
@Configuration
public class CorsInterceptor implements HandlerInterceptor {
    @Autowired
    private ParamConfig paramConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理中文乱码
        // 处理post请求的中文乱码
        request.setCharacterEncoding("utf-8");
        // 处理响应的字符集中文乱码
        response.setCharacterEncoding("utf-8");
        // 处理浏览器字符集中文乱码
        response.setContentType("text/html;charset=utf-8");
        String requestMethod = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(requestMethod)) {
            // ajax跨域
            response.setHeader("Access-Control-Allow-Origin", paramConfig.getAccessControlAllowOrigin());
            response.setHeader("Access-Control-Allow-Methods", paramConfig.getAccessControlAllowMethods());
            response.setHeader("Access-Control-Max-Age", paramConfig.getAccessControlAllowMaxAge());
            response.setHeader("Access-Control-Allow-Headers", paramConfig.getAccessControlAllowHeaders());
            response.setHeader("Access-Control-Allow-Credentials", paramConfig.getAccessControlAllowCredentials());
            return false;
        }
        // ajax跨域
        // response.setHeader("Access-Control-Allow-Origin", paramConfig.getAccessControlAllowOrigin());
        // response.setHeader("Access-Control-Allow-Methods", paramConfig.getAccessControlAllowMethods());
        // response.setHeader("Access-Control-Max-Age", paramConfig.getAccessControlAllowMaxAge());
        // response.setHeader("Access-Control-Allow-Headers", paramConfig.getAccessControlAllowHeaders());
        // response.setHeader("Access-Control-Allow-Credentials", paramConfig.getAccessControlAllowCredentials());
        return HandlerInterceptor.super.preHandle(request, response, handler);
        // return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
